package com.ly.mpayment.persist.task;

import cn.hutool.http.ContentType;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ly.mpayment.persist.task.enums.SendMessageType;
import com.ly.mpayment.persist.task.model.EnterpriseWeChatRobotParam;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;

/**
 * 企业微信群机器人 消息处理器
 *
 * @author 3y
 */
@Slf4j
public class EnterpriseWeChatRobotHandler {

    public static String robotUrl = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=";

    public static boolean handler(String webHook, String content) {
        try{
            EnterpriseWeChatRobotParam enterpriseWeChatRobotParam = assembleParam(content);
            String result = HttpRequest.post(robotUrl + webHook)
                    .header(Header.CONTENT_TYPE.toString(), ContentType.JSON.toString())
                    .body(JSON.toJSONString(enterpriseWeChatRobotParam))
                    .timeout(2000)
                    .execute().body();
            JSONObject jsonObject = JSON.parseObject(result);
            if (jsonObject.getInteger("errcode") == 0) {
                return true;
            }
            log.error("EnterpriseWeChatRobotHandler#handler fail! result:{},params:{}", JSON.toJSONString(jsonObject), content);
        } catch (Exception e) {
            log.error("EnterpriseWeChatRobotHandler#handler fail!e:{},params:{}", content);
        }
        return false;
    }

    private static EnterpriseWeChatRobotParam assembleParam(String content) {
        EnterpriseWeChatRobotParam param = EnterpriseWeChatRobotParam.builder()
                .msgType(SendMessageType.getEnterpriseWeChatRobotTypeByCode("10")).build();
        param.setText(EnterpriseWeChatRobotParam.
                TextDTO.builder()
                .content(content)
                .mentionedMobileList(Arrays.asList("@all"))
                .build());
        return param;
    }

    public static void main(String[] args) {
        System.out.println(EnterpriseWeChatRobotHandler.handler("e6f81c0b-4a50-4952-9c77-de724124df0f", "1822卡单，青海移动，上游文航\n1822卡单，辽宁移动，上游方木"));
    }
}

